package com.iphone.extra;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import com.iphone.extra.view.IWidgetFrameLayout;
import com.iphone.extra.view.ShortcutWidgetLayout;

import java.util.Calendar;

public class WidgetClockLayout extends IWidgetFrameLayout {

    private boolean isRegisterTimer = true;
    private final IntentFilter mTimeFilter = new IntentFilter();

    private ImageView mIconHour;
    private ImageView mIconMinute;
    private ImageView mIconSecond;

    public WidgetClockLayout(Context context) {
        this(context, null, 0);
    }

    public WidgetClockLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WidgetClockLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mIconHour = (ImageView) findViewById(R.id.clock_icon_hour);
        mIconMinute = (ImageView) findViewById(R.id.clock_icon_minute);
        mIconSecond = (ImageView) findViewById(R.id.clock_icon_second);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        getContext().registerReceiver(mScreenReceiver, filter);

        isRegisterTimer = true;
        mTimeFilter.addAction(Intent.ACTION_TIME_CHANGED);
        mTimeFilter.addAction(Intent.ACTION_TIME_TICK);
        mTimeFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        getContext().registerReceiver(mTimerReceiver, mTimeFilter);

        updateClock();
        startSecondAnimation();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (isRegisterTimer) {
            isRegisterTimer = false;
            getContext().unregisterReceiver(mTimerReceiver);
        }
        getContext().unregisterReceiver(mScreenReceiver);

        mIconSecond.clearAnimation();
    }

    private void updateClock() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int seconds = calendar.get(Calendar.SECOND);
        float minutes = calendar.get(Calendar.MINUTE) + seconds / 60.0F;
        float hours = calendar.get(Calendar.HOUR_OF_DAY) + minutes / 60.0F;

        mIconHour.setRotation(hours / 12.0f * 360.0f);
        mIconMinute.setRotation((minutes / 60.0f * 360.0f));
    }

    private void startSecondAnimation() {
        RotateAnimation rotate = new RotateAnimation(0, 359, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setRepeatCount(-1);
        rotate.setDuration(60 * 1000);
        rotate.setRepeatMode(Animation.RESTART);
        rotate.setInterpolator(new LinearInterpolator());
        mIconSecond.startAnimation(rotate);
    }

    private final BroadcastReceiver mTimerReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            updateClock();
        }
    };

    private final BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                isRegisterTimer = false;
                mIconSecond.clearAnimation();
                getContext().unregisterReceiver(mTimerReceiver);
            } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
                if (!isRegisterTimer) {
                    isRegisterTimer = true;
                    startSecondAnimation();
                    getContext().registerReceiver(mTimerReceiver, mTimeFilter);
                }
            }
        }
    };

    @Override
    public boolean onCellClicked(String describe) {
        try {
            Intent intent = new Intent();
            intent.setClassName("com.aedesign.deskclock", "com.aedesign.deskclock.DeskClockGroupActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            getContext().startActivity(intent);
            getContext().sendBroadcast(new Intent(ShortcutWidgetLayout.ACTION));
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public String getLabel(Resources res) {
        return res.getString(R.string.widget_label_clock);
    }
}
